// pages/ai/ai.js
Page({
  data: {
    userImage: '',
    selectedClothing: null,
    processing: false,
    progress: 0,
    aiResult: '',
    
    // 服装列表
    clothingList: [
      { id: 1, name: '时尚连衣裙', price: 299 },
      { id: 2, name: '休闲T恤', price: 89 },
      { id: 3, name: '牛仔裤', price: 199 },
      { id: 4, name: '针织衫', price: 159 },
      { id: 5, name: '运动装', price: 259 }
    ],
    
    // 历史记录
    historyList: [
      {
        id: 1,
        result: '/images/history1.jpg',
        time: '2小时前',
        clothingName: '时尚连衣裙'
      },
      {
        id: 2,
        result: '/images/history2.jpg',
        time: '1天前',
        clothingName: '休闲T恤'
      }
    ]
  },

  onLoad(options) {
    console.log('AI换装页面加载')
    
    // 如果从商品页面跳转过来，预选商品
    if (options.productId) {
      this.setData({
        selectedClothing: parseInt(options.productId)
      })
    }
  },

  onShow() {
    console.log('AI换装页面显示')
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.setData({
          userImage: tempFilePath,
          aiResult: '' // 清空之前的结果
        })
        
        wx.showToast({
          title: '照片上传成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 选择服装
  selectClothing(e) {
    const clothingId = e.currentTarget.dataset.id
    this.setData({
      selectedClothing: clothingId,
      aiResult: '' // 清空之前的结果
    })
    
    const clothing = this.data.clothingList.find(item => item.id === clothingId)
    wx.showToast({
      title: `已选择${clothing.name}`,
      icon: 'none'
    })
  },

  // 开始AI换装
  startAI() {
    if (!this.data.userImage || !this.data.selectedClothing) {
      wx.showToast({
        title: '请先上传照片并选择服装',
        icon: 'none'
      })
      return
    }

    this.setData({
      processing: true,
      progress: 0
    })

    // 模拟AI处理进度
    this.simulateAIProgress()
  },

  // 模拟AI处理进度
  simulateAIProgress() {
    const timer = setInterval(() => {
      let progress = this.data.progress + Math.random() * 20
      
      if (progress >= 100) {
        progress = 100
        clearInterval(timer)
        
        // 模拟AI处理完成
        setTimeout(() => {
          this.setData({
            processing: false,
            aiResult: this.data.userImage, // 这里应该是AI处理后的结果图片
            progress: 0
          })
          
          wx.showToast({
            title: 'AI换装完成',
            icon: 'success'
          })
          
          // 添加到历史记录
          this.addToHistory()
        }, 500)
      }
      
      this.setData({ progress })
    }, 200)
  },

  // 重新生成
  retryAI() {
    this.setData({
      aiResult: ''
    })
    this.startAI()
  },

  // 保存结果
  saveResult() {
    if (!this.data.aiResult) {
      return
    }

    wx.saveImageToPhotosAlbum({
      filePath: this.data.aiResult,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('保存失败:', err)
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  },

  // 添加到历史记录
  addToHistory() {
    const clothing = this.data.clothingList.find(item => item.id === this.data.selectedClothing)
    const newHistory = {
      id: Date.now(),
      result: this.data.aiResult,
      time: '刚刚',
      clothingName: clothing.name
    }
    
    const historyList = [newHistory, ...this.data.historyList]
    this.setData({ historyList })
    
    // 保存到本地存储
    wx.setStorageSync('aiHistory', historyList)
  },

  // 查看历史记录
  viewHistory(e) {
    const item = e.currentTarget.dataset.item
    
    wx.previewImage({
      current: item.result,
      urls: [item.result]
    })
  },

  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '是否要清空所有历史记录？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            historyList: []
          })
          wx.removeStorageSync('aiHistory')
          wx.showToast({
            title: '已清空历史记录',
            icon: 'success'
          })
        }
      }
    })
  }
})
